package scatter.area.rest.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import scatter.area.pojo.po.Area;
import scatter.area.rest.service.IAreaService;
import scatter.common.rest.tools.InterfaceTool;
import scatter.common.rest.trans.ITransService;
import scatter.common.rest.trans.TransResult;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 区域翻译实现
 * </p>
 *
 * @author yw
 * @since 2020-11-27
 */
@Component
public class AreaTransServiceImpl implements ITransService<Object,String>, InterfaceTool {

    @Autowired
    private IAreaService areaService;

    @Override
    public boolean support(String type) {
        return isEqualAny(type,Area.TRANS_AREA_BY_ID
                ,Area.TRANS_AREA_PARENT_BY_ID
        ,Area.TRANS_AREA_AND_PARENTS_BY_ID);
    }

    @Override
    public TransResult<Object, String> trans(String type, String key) {
        if (isEqual(type,Area.TRANS_AREA_BY_ID)) {
            Area byId = areaService.getById(key);
            return new TransResult(byId,key);
        } else if (isEqual(type,Area.TRANS_AREA_PARENT_BY_ID)) {
            Area byId = areaService.getParent(key);
            return new TransResult(byId,key);
        } else if (isEqual(type,Area.TRANS_AREA_AND_PARENTS_BY_ID)) {
            Area area = areaService.getAllById(key);
            return new TransResult(area,key);
        }
        return null;
    }

    @Override
    public boolean supportBatch(String type) {
        return support(type);
    }

    @Override
    public List<TransResult<Object, String>> transBatch(String type, Set<String> keys) {
        if (isEqual(type,Area.TRANS_AREA_BY_ID)) {
            return areaService.listByIds(keys).stream().map(item->new TransResult<Object, String>(item,item.getId())).collect(Collectors.toList());
        }else if (isEqual(type,Area.TRANS_AREA_PARENT_BY_ID)) {
            List<Area> areas = areaService.listByIds(keys);
            if (!isEmpty(areas)) {
                return areaService.listByIds(areas.stream().map(Area::getParentId).collect(Collectors.toSet())).stream().map(item->new TransResult<Object, String>(item,item.getId())).collect(Collectors.toList());
            }
        }else if (isEqual(type,Area.TRANS_AREA_AND_PARENTS_BY_ID)) {
            List<Area> areas = areaService.getAllByIds(keys);
            if (!isEmpty(areas)) {
                return areas.stream().map(item->new TransResult<Object, String>(item,item.getId())).collect(Collectors.toList());
            }
        }
        return null;
    }
}
